package com.dong.springbootdruidmultiple;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;


@SpringBootApplication
public class SpringBootDruidMultipleApplication implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(SpringBootDruidMultipleApplication.class);

    @Resource(name = "ordersDataSource")
    private DataSource ordersDataSource;

    @Resource(name = "usersDataSource")
    private DataSource usersDataSource;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDruidMultipleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // orders 数据源
        logger.info("[run][获得数据源：{}]", ordersDataSource.getClass());

        // users 数据源
        logger.info("[run][获得数据源：{}]", usersDataSource.getClass());

        // 建立连接 不然无法localhost:8080/druid 访问显示数据源
        try (Connection conn = ordersDataSource.getConnection()) {
            // orders 数据源
            logger.info("[run][ordersDataSource获得连接：{}]", conn);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try (Connection conn = usersDataSource.getConnection()) {
            // orders 数据源
            logger.info("[run][usersDataSource获得连接：{}]", conn);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
